<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\RequestLog as LogModel;
class RequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $data = $request->except('TOKEN_USER');
        $url  = $request->getRequestUri();
        $log = LogModel::create([
            'url'       => $url,
            'request'   => json_encode($data)
        ]);

        // 暂存日志ID
        $request->offsetSet('SIP_LOG_ID', $log->id);
        try {

            return $next($request);

        } catch (\Throwable  $e) {

            $log->update(['response' => '系统错误:'.$e->getMessage()]);
            return response()->json(['code' => 501, 'msg' => '系统出错']);
        }
    }
}
